﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Core;

namespace ZoneLineNew.Common {
    public class ApiHelper {

        private static string getStationInfoUrl = "/api/Interaction/GetStationList";

        private static string getStationDataUrl = "/api/Interaction/GetStationData";

        private static int apiRequestTimeOut = AppSession.Config.ApiRequestTimeOut;
        #region Props

        //public static bool IsOpenCheck { get; set; } = true;

        #endregion


        #region Methods

        public static async Task<StationInfoResults> GetStaionInfo(string serverip) {
            using (HttpClient client = new HttpClient()) {
                client.Timeout = TimeSpan.FromSeconds(apiRequestTimeOut);
                var content = new StringContent("{}", Encoding.UTF8, "application/json");
                var postResult = await client.PostAsync(serverip + getStationInfoUrl, content);
                postResult.EnsureSuccessStatusCode();
                var temp = await postResult.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<StationInfoResults>(temp);
                result.IsSuccess = true;
                return result;
            }
        }

        public static async Task<(StationDataResult, string)> GetStationData(string body, string serverip) {
            if (string.IsNullOrEmpty(body)) {
                throw new Exception("Para is null");
            }
            using (HttpClient client = new HttpClient()) {
                client.Timeout = TimeSpan.FromSeconds(apiRequestTimeOut);

                var para = new { Body = new { } };
                var content = new StringContent(body, Encoding.UTF8, "application/json");
                var postResult = await client.PostAsync(serverip + getStationDataUrl, content);
                postResult.EnsureSuccessStatusCode();
                var temp = postResult.Content.ReadAsStringAsync().Result;
                var result = JsonConvert.DeserializeObject<StationDataResult>(temp);
                result.IsSuccess = true;
                return (result, temp);

            }
        }

        /// <summary>
        /// 检查来料是否合格
        ///  因所有他们接口的来料数据验证都放在的OP210上，所以从OP210获取，OP210的stationId=1660878007713275904(固定的，除非他们改了)
        /// </summary>
        /// <param name="absScanCode">油缸码</param>
        /// <param name="stationDataResult">其他需要验证的数据，可合并其他站数据结合验证，目前垫片工位需要</param>
        /// <param name="serverip">ip url</param>
        /// <returns></returns>
        public static async Task<(bool IsOk, string errorMsg)> CheckIncomingMaterialIsOKAsync(string absScanCode, StationDataResult stationDataResult = null, string serverip = "http://172.20.27.12:8089") {
            try {
                if (AppSession.Config.IsEnabledMaterialVerify) {
                    using (HttpClient client = new HttpClient()) {
                        client.Timeout = TimeSpan.FromSeconds(apiRequestTimeOut);
                        var queryStr = $"{{\"Body\":\"{{stationId:\\\"{"1660878007713275904"}\\\",masterCode:\\\"{absScanCode}\\\"}}\"}}";
                        var content = new StringContent(queryStr, Encoding.UTF8, "application/json");
                        LogManager.Info("来料数据检查请求：" + await content.ReadAsStringAsync());
                        var postResult = await client.PostAsync(serverip + getStationDataUrl, content);
                        postResult.EnsureSuccessStatusCode();
                        var temp = postResult.Content.ReadAsStringAsync().Result;
                        LogManager.Info("来料数据检查结果：" + temp);
                        var result = JsonConvert.DeserializeObject<StationDataResult>(temp);
                        result.IsSuccess = true;
                        if (result.IsSuccess && result.data.Count > 0) {
                            //var manyData = new List<StationData>();
                            //manyData.AddRange(result.data);
                            //if (stationDataResult != null && stationDataResult.data.Count > 0)
                            //{
                            //    manyData.AddRange(stationDataResult.data.Where(o => o.parameterConfigName != "节拍"));
                            //}
                            //if (manyData.Any(o => o.resultCode != "1"))
                            //{
                            //    return (false, "来料MES接口数据请求结果检查NG！");
                            //}
                            //else
                            //{
                            //    return (true, "来料MES接口数据请求结果检查OK");
                            //}
                            //2025-06-24 修改，客户要求不需要验证NG、OK，只需要验证数据是否存在
                            return (true, "来料MES接口数据请求结果检查OK");
                        }
                        return (false, $"来料MES接口数据返回异常！{temp}");
                    }
                } else {
                    return (true, "跳过来料MES检查");
                }
            } catch (Exception ex) {
                return (false, ex.Message);
            }
        }

        /// <summary>
        /// 综合检具
        /// </summary>
        /// <returns></returns>
        public static async Task<(bool IsOk, string errorMsg)> ComprehensiveCheckAsync(string absScanCode, string serverip = "http://172.20.27.12:8089") {
            try {
                //TODO

                await Task.Delay(1000);

                return (false, "综合检具接口数据返回异常，TODO！");
            } catch (Exception ex) {
                return (false, ex.Message);
            }
        }

        #endregion
    }

    #region 实体类

    public class OperateResult {
        public string ErrInfo { get; set; }

        public bool IsSuccess { get; set; }

        public string Result { get; set; }
    }

    public class OperateResultBase {
        public int errCode { get; set; }

        public bool status { get; set; }

        public string errMessage { get; set; }

        public bool IsSuccess { get; set; }

        public string QueryErrMsg { get; set; }
    }

    public class StationInfoResults : OperateResultBase {
        public OperateResultDDBase data { get; set; }
    }

    public class OperateResultDDBase {
        public List<StationInfo> list { get; set; }
    }

    public class StationInfo {
        public long id { get; set; }

        public int code { get; set; }

        public string name { get; set; }
    }


    public class StationDataResult : OperateResultBase {
        public List<StationData> data { get; set; }
    }

    public class StationData {
        public string parameterConfigName { get; set; }

        public string parameterValue { get; set; }

        public string stationName { get; set; }
        public string resultCode { get; set; }
    }
    #endregion
}
